package org.grow.wsing.stomp;

import org.grow.wsing.domain.ChatMessage;
import org.grow.wsing.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 2025/10/20
 */

//处理stomp协议的controller 也叫handler
@RestController
public class ChatMessageController {

    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    //    @RequestMapping@GetMapping 针对http 请求url 匹配
//    前端 /chatMessage/insert
//     registry.setApplicationDestinationPrefixes("/chatMessage"); + @MessageMapping("/insert")
    @MessageMapping("/insert")
//    {"content":"dd","groupId":"001","sender":"zhangsan","msgTime":null}
    public String insert(ChatMessage chatMessage, Principal principal) {
        System.out.println("---------???" + chatMessage);
//        jwt token解析出来
        System.out.println("当前登录人是？" + principal.getName());
        chatMessage.setSender(principal.getName());
        chatMessage.setMsgId(0);
        chatMessage.setMsgTime(LocalDateTime.now());
        chatMessageService.save(chatMessage);
        simpMessagingTemplate.convertAndSend("/channel/" + chatMessage.getGroupId(), chatMessage);
        return "";
    }

    ///chatMessage/personal
    @MessageMapping("/personal")
    public String p2pchat(ChatMessage chatMessage, Principal principal) {
        chatMessage.setSender(principal.getName());
        chatMessage.setMsgId(0);
        chatMessage.setMsgTime(LocalDateTime.now());
        chatMessageService.save(chatMessage);
//        前端订阅地址 /single/p2p/007
        simpMessagingTemplate.convertAndSendToUser(chatMessage.getGroupId(), "/p2p/007", chatMessage);
        return "";
    }

//    @MessageMapping("/insert2")
////    {"content":"dd","groupId":"001","sender":"zhangsan","msgTime":null}
//    public String insert2(ChatMessage chatMessage) {
//        System.out.println("---------???"+chatMessage);
//
//        simpMessagingTemplate.convertAndSend("/channel/"+chatMessage.getGroupId(),chatMessage);
//        return "";
//    }
}
